//
//  UITestWebViewController.m
//  aestest
//
//  Created by yaoziyang on 14-7-10.
//  Copyright (c) 2014年 yaoziyang. All rights reserved.
//

#import "TestWebViewController.h"
#import "ViewFileListController.h"
#import "OpenFileNavigationController.h"
#import "NSDataEncrypt.h"
#import <math.h>

NSString* KEY = @"5a987f8e1fb029";

@interface TestWebViewController ()<NSURLConnectionDelegate, NSURLConnectionDataDelegate>
{
    NSURL* currentURL;
}
@end

@implementation TestWebViewController
{
    NSURLConnection* testConn;
    NSOperationQueue* testQueue;
}
@synthesize webView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"打开文件" style:UIBarButtonItemStylePlain target:self action:@selector(navigateToOpenFile:)];
    
    self.navigationController.delegate = self;
    
    self.webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    self.webView.delegate = self;
    [self.view addSubview:self.webView];
    
    NSString* userAgentValue = @"Mozilla/5.0 (iPhone; CPU iPhone OS 7_1 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Mobile/11D167 (341387408)";
    NSString* authValue = @"Basic k==";
    NSString* urlString = @"http://m.changan.com.cn/mam/api/mam/clients/files/noVePBHjHyJj1jOm?appkey=367f03be13b5e0ce18e8ae45b9091541";
    //NSString* urlString = @"http://www.baidu.com";
    //NSString* urlString = @"http://61.186.243.102/cameap/app";
    NSURL* url = [NSURL URLWithString:urlString];
    
    NSMutableURLRequest* request = [[NSMutableURLRequest alloc]initWithURL:url];
    
    [request setValue:@"XMLHttpRequest" forHTTPHeaderField:@"X-Requested-With"];
    [request setValue:userAgentValue forHTTPHeaderField:@"User-Agent"];
    //[request setValue:authValue forHTTPHeaderField:@"Authorization"];
    
    //[request setValue:@"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8" forHTTPHeaderField:@"Accept"];
    //[request setValue:@"gzip,deflate,sdch" forHTTPHeaderField:@"Accept-Encoding"];
    //[request setValue:@"zh-CN,zh;q=0.8" forHTTPHeaderField:@"Accept-Language"];
    //[request setValue:@"keep-alive" forHTTPHeaderField:@"Connection"];
    //[request setValue:@"61.186.243.102" forHTTPHeaderField:@"Host"];
    //[request setValue:@"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36" forHTTPHeaderField:@"User-Agent"];
    
    testQueue = [[NSOperationQueue alloc]init];
    testConn = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
    [testConn setDelegateQueue:testQueue];
    
    dispatch_async(
                   dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, (unsigned long)NULL),
                   ^(void) { [testConn start];}
                   );
    
    /*NSString* str = @"abcdefghijklmnopqrstuvwxyz123456c";
    //NSString* str = @"fsadfsdafsdafsdafsadfsadfsadfaaa";
    NSData* tmd5key = [KEY md5Data];
    NSData* result = [[str dataUsingEncoding:NSUTF8StringEncoding] aesEncrypt:tmd5key];
    
    NSData* deresult = [result aesDecrypt:tmd5key];
    NSLog(@"%@", [[NSString alloc] initWithData:deresult encoding:NSUTF8StringEncoding]);
    
    NSData* deresult1 = [[NSData parseHexString:@"acedc5e002e3e13b7eb41e13178be87cd65edc41d7925553bee4185e4504494280875276278bfc502c455227b7c7a391"]
                         aesDecrypt:tmd5key];
    NSLog(@"%@", [[NSString alloc] initWithData:deresult1 encoding:NSUTF8StringEncoding]);
    
    NSData* deresult2 = [[NSData parseHexString:@"acedc5e002e3e13b7eb41e13178be87cd50ae81d2dc0383518fd7750478a4ef1"] aesDecrypt:tmd5key];
    NSLog(@"%@", [[NSString alloc] initWithData:deresult2 encoding:NSUTF8StringEncoding]);
    
    NSData* data = [NSData aesEncryptFile:[NSURL fileURLWithPath:@"/Users/yaoziyang/develop/ichangan-develop/aestest/www/ios_test/test.html"] key:[KEY md5Data]];
    BOOL ret = [data writeToFile:@"/Users/yaoziyang/develop/ichangan-develop/aestest/www/test_ios_enc.html" atomically:YES];
    assert(ret);
    
    data = [NSData aesEncryptFile:[NSURL fileURLWithPath:@"/Users/yaoziyang/develop/ichangan-develop/aestest/www/ios_test/testimg/login.png"] key:[KEY md5Data]];
    ret = [data writeToFile:@"/Users/yaoziyang/develop/ichangan-develop/aestest/www/testimg/login.png" atomically:YES];
    assert(ret);
    
    data = [NSData aesEncryptFile:[NSURL fileURLWithPath:@"/Users/yaoziyang/develop/ichangan-develop/aestest/www/ios_test/testjs/hello.js"] key:[KEY md5Data]];
    ret = [data writeToFile:@"/Users/yaoziyang/develop/ichangan-develop/aestest/www/testjs/hello.js" atomically:YES];
    assert(ret);
    
    //NSString* test = @"/Users/yaoziyang/Library/Application Support/iPhone Simulator/6.1/Applications/3855A0B8-0085-4B88-9ADA-6897FDBCD6B9/Documents/用餐信息6ef7453fc50c96d5af9c2e4d9f7c66de5.jpg";
    
    /*NSString* test = @"/Users/yaoziyang/Library/Application Support/iPhone Simulator/6.1/Applications/3855A0B8-0085-4B88-9ADA-6897FDBCD6B9/Documents/用餐信息.jpg";
    
    FILE* fp = fopen([test cStringUsingEncoding:NSUTF8StringEncoding], "w+");
    fwrite([test cStringUsingEncoding:NSUTF8StringEncoding], test.length, 1, fp);
    fclose(fp);
    
    NSFileHandle* handle = [NSFileHandle fileHandleForWritingAtPath:test];
    [handle writeData:[NSData dataWithBytes:[test cStringUsingEncoding:NSUTF8StringEncoding] length: test.length]];
    [handle closeFile];*/
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"status code: %d", [((NSHTTPURLResponse*) response) statusCode]);
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"status code: %@", error.description);
}

- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
{
    NSLog(@"data received: %d", [data length]);
    
    [data writeToFile:@"/Users/yaoziyang/develop/Temp/test.zip" atomically:YES];
}

- (void)openEncryptedFile:(NSURL*)url
{
    @try {
        NSData* data = [NSData aesDecryptFile:url key:[KEY md5Data]];
        NSString* content = [[NSString alloc] initWithData:data  encoding:NSUTF8StringEncoding];
        NSLog(@"%@", content);
        [self.webView loadHTMLString:content  baseURL:nil];
    }
    @catch (NSException *exception) {
        NSString* msg = [NSString stringWithFormat:@"解密错误:%@", [exception reason]];
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"错误" message: msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    }
}

- (void)navigateToOpenFile:(id)sender
{
    NSURL* wwwURL = [[NSBundle mainBundle].bundleURL URLByAppendingPathComponent:@"www" isDirectory:YES];
    ViewFileListController* controller = [[ViewFileListController alloc] initWithTargetFolder:wwwURL];
    [self.navigationController pushViewController:controller animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    NSLog(@"start load");
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSLog(@"finish load");
    
    /*NSString *lJs = @"document.documentElement.innerHTML";
    NSString *lHtml1 = [self.webView stringByEvaluatingJavaScriptFromString:lJs];
    
    NSLog(@"%@", lHtml1);*/
    
    [self.webView stringByEvaluatingJavaScriptFromString:@"SayHello('aaaa')"];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    NSLog(@"load error:%@", error.description);
}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    if (viewController == self) {
        OpenFileNavigationController* ofController = (OpenFileNavigationController*)navigationController;
        if (![ofController.goURL isEqual:currentURL] && [ofController.goURL isFileURL]) {
            
            /*NSLog(@"%@", ofController.goURL);
            NSData* data = [NSData aesDecryptFile:ofController.goURL key:[KEY md5Data]];
            NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);*/
            
            NSURLRequest* request = [NSURLRequest requestWithURL:ofController.goURL];
            [self.webView loadRequest:request];
        }
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
